<?php

namespace app\admin\controller;

use app\common\controller\AdminBaseController;
use Jrk\Tree;
use think\Exception;
use think\facade\Db;
use think\facade\Config;
use think\facade\Route;
use think\Request;
use app\admin\service\ExcelService;
use app\admin\model\ArticleCates;

class Remote extends AdminBaseController
{

    protected function initialize()
    {
        parent::initialize();
        $conparas = [
            // 数据库类型
            'type'            => 'mysql',
            // 服务器地址
            'hostname'        => '1.117.206.202',
            // 数据库名
            'database'        => 'dianpu',
            // 用户名
            'username'        => 'dianpu',
            // 密码
            'password'        => 'KAWCHTZjmppinLr2',
            // 端口
            'hostport'        => '35654',
        ];
        $database_config = Config::get('database');
        $database_config['connections']['dynamic']= $conparas;
        $config = Config::set($database_config, 'database');
        $this->table = $this->request->get('table');
    }

    public function index(){
        if (IS_AJAX){
            try {
                $page = input('page');
                $limit = input('limit');
                $param = input();
                $where = [];
                // if (isset($param['name']) && $param['name'] != '') {
                //     $where[] = ['name', 'like', "%" . $param['name'] . "%"];
                // }
                // if (isset($param['type']) && $param['name'] != '') {
                //     $where[] = ['type', 'like', "%" . $param['type'] . "%"];
                // }
                // if (isset($param['time']) && $param['time'] != '') {
                //     $ck = @explode(" ~ ", $param['time']);
                //     $b = $ck[0] . " 00:00:00";
                //     $e = $ck[1] . " 23:59:59";
                //     $where[] = ['create_time', 'between', [strtotime($b), strtotime($e)]];
                // }
                $count = Db::connect('dynamic')->table($this->table)->field('id,uid,name,location,pname,cityname,adname,address,business_area,type,tag,tel,cost,rating')->where($where)->count('uid');
                $data = Db::connect('dynamic')->name($this->table)
                    ->where($where)
                    ->limit($page*$limit,$limit)
                    ->select();
                $result = [
                    'code' => 0,
                    'msg'  => 'ok',
                    'time' => time(),
                    'data' => $data,
                    'count'=> $count
                ];
                return json($result);
            } catch (Exception $exception) {
                $result = [
                    'code' => 100,
                    'msg'  => $exception->getMessage(),
                    'time' => time(),
                    'data' => [],
                    'count'=> 0
                ];
                return json($result);
            }
        }
        return $this->fetch();
    }

    public function pull()
    {
        if(IS_AJAX){
            $param = $this->request->post();
            if(empty($param['modelid']) || empty($param['cateid'])){
                return json(['msg'=>'请选择模型和栏目','code'=>0]);
            }
            $where = [];
            $where[] = ['is_use','=',0];
            // if (isset($param['dalei']) && $param['dalei'] != '') {
            //     $where[] = ['dalei', '=', $param['dalei']];
            // }
            // if (isset($param['zhonglei']) && $param['zhonglei'] != '') {
            //     $where[] = ['zhonglei', '=', $param['zhonglei']];
            // }
            // if (isset($param['xiaolei']) && $param['xiaolei'] != '') {
            //     $where[] = ['xiaolei', '=', $param['xiaolei']];
            // }
            if (isset($param['type']) && $param['type'] != '') {
                $where[] = ['type', '=', $param['type']];
            }
            if (isset($param['keyword']) && $param['keyword'] != '') {
                $where[] = ['name', 'like', "%" . $param['keyword'] . "%"];
            }
            if (isset($param['cityname']) && $param['cityname'] != '') {
                $where[] = ['cityname', '=', $param['cityname']];
            }
            $limit = 100;
            if($param['num']<=100){
                $limit = $param['num'];
            }
            $data = Db::connect('dynamic')->name($this->table)->where($where)->where("!LOCATE('|',type)")->limit($limit)->select();
            if(empty($data)){
                return json(['msg'=>'没有数据','code'=>0]);
            }
            $mod = Db::name('articles_models')->field('tablename')->find($param['modelid']);
            $count = 0;
            foreach($data as $v){
                $time = time();
                $area = $this->matchArea($v['pname'],$v['cityname'],$v['adname']);
                Db::name($mod['tablename'])->insert([
                    'cate_id' => $param['cateid'],
                    'uid' => $v['uid'],
                    'name' => $v['name'],
                    'location' => $v['location'],
                    'pname' => $v['pname'],
                    'cityname' => $v['cityname'],
                    'adname' => $v['adname'],
                    'pcode' => $v['pcode'],
                    'citycode' => $v['citycode'],
                    'adcode' => $v['adcode'],
                    'address' => $v['address'],
                    'business_area' => $v['business_area'],
                    'type' => $v['type'],
                    'tag' => $v['tag'],
                    'tel' => $v['tel'],
                    'cost' => $v['cost'],
                    'rating' => $v['rating'],
                    'photos' => $v['photos'],
                    'create_time' => $time,
                    'update_time' => $time,
                    'hits' => mt_rand(300,900),
                    'areaid1' => $area['areaid1'],
                    'areaid2' => $area['areaid2'],
                    'areaid3' => $area['areaid3'],
                    'is_show' => 0,
                ]);
                Db::connect('dynamic')->name($this->table)->where('id',$v['id'])->update([
                    'is_use' => 1
                ]);
                $count++;
            }
            if($count < 100 || $param['num']<=100){
                return json(['msg'=>'执行完毕','code'=>0]);
            }else{
                $next_num = $param['num'] - $count;
                return json(['msg'=>'正在执行，本次执行个数:'.$count.'，剩余数量:'.$next_num,'code'=>1,'data'=>['num'=>$next_num]]);
            }
            
        }else{
            $cate = Tree::toFormatTree(ArticleCates::select()->toArray(), "name");
            $models = Db::name('articles_models')->where([
                ['id','>',2]
            ])->select();
            $this->assign("models", $models);
            return $this->fetch();
        }
    }

    private function matchArea($name1='',$name2='',$name3=''){
        $area = [
            'areaid1' => 0,
            'areaid2' => 0,
            'areaid3' => 0
        ];
        if(!empty($name1)){
            $area1 = Db::name('area')->field('id')->where('pid',0)->where("instr('$name1',name)")->find();
            if(!empty($area1)){
                $area['areaid1'] = $area1['id'];
                if(!empty($name2)){
                    $area2 = Db::name('area')->field('id')->where('pid',$area['areaid1'])->where("instr('$name2',name)")->find();
                    if(!empty($area2)){
                        $area['areaid2'] = $area2['id'];
                        if(!empty($name3)){
                            $area3 = Db::name('area')->field('id')->where('pid',$area['areaid2'])->where("instr('$name3',name)")->find();
                            if(!empty($area3)){
                                $area['areaid3'] = $area3['id'];
                            }
                        }
                    }
                }
            }
        }
        return $area;
    }

}